#!/usr/bin/env ruby

require 'rubygems'
require 'yaml'
require 'json'

unless ARGV[0]
  STDERR.puts "First argument must be a file name or '-' !"
  exit 1
end
unless ARGV[1]
  STDERR.puts "Second argument must be the name of the hash"
  exit 1
end
tree = nil
if ARGV[0] == '-'
  tree = JSON.parse STDIN.read
elsif File.exists? ARGV[0]
  case ARGV[0].split('.')[-1]
  when "yml","yaml"
    tree = YAML.load_file ARGV[0]
  when "json"
    File.open(ARGV[0]) do |f|
      tree = JSON.parse(f.read)
    end
  end
else
  STDERR.puts "#{ARGV[0]} does not exist!"
end

def walk (t, res, key)
  if t.respond_to? :keys
    indexes=t.keys
  elsif t.kind_of? Array
    indexes=[]
    t.each_index {|i| indexes.push i}
  else
    STDERR.puts "walk was passed something that was not an array or a hash!"
    exit 1
  end
  indexes.each { |i|
    if key.length == 0
      k="#{i}"
    else
      k="#{key}.#{i}"
    end
    if t[i].kind_of? Array or t[i].kind_of? Hash
      walk(t[i],res,k)
    elsif t[i].kind_of? NilClass
      next
    else
      puts "#{res}['#{k}']=$'#{t[i].to_s.gsub(/'/,"\\\\'")}'"
    end
  }
end

walk(tree,ARGV[1], '')
